package com.railway.switchs.action.business;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.railway.switchs.aspect.OperationLog;
import com.railway.switchs.base.BaseResponse;
import com.railway.switchs.config.ExcelListener;
import com.railway.switchs.constant.FileConstant;
import com.railway.switchs.constant.SystemConstant;
import com.railway.switchs.domain.dto.business.BaseInfo;
import com.railway.switchs.domain.dto.business.RoadSwitch;
import com.railway.switchs.domain.dto.business.SwitchInfo;
import com.railway.switchs.domain.pojo.business.RoadSwitchPojo;
import com.railway.switchs.domain.query.business.BaseDeviceQuery;
import com.railway.switchs.domain.query.business.BaseInfoQuery;
import com.railway.switchs.domain.query.business.RoadSwitchQuery;
import com.railway.switchs.domain.query.business.SwitchInfoQuery;
import com.railway.switchs.domain.query.user.UserInfoQuery;
import com.railway.switchs.domain.response.FileUploadResponse;
import com.railway.switchs.enums.*;
import com.railway.switchs.service.business.IBaseDeviceService;
import com.railway.switchs.service.business.IBaseInfoService;
import com.railway.switchs.service.business.IRoadSwitchService;
import com.railway.switchs.service.business.ISwitchInfoService;
import com.railway.switchs.service.user.IUserInfoService;
import com.railway.switchs.utils.DateUtil;
import com.railway.switchs.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName RoadSwitchAction
 * @Author 魏梓晟
 * @Version 1.0
 **/
@Controller
@Slf4j
@RequestMapping("/back/roadSwitch")
public class RoadSwitchAction {

    @Autowired
    private IRoadSwitchService roadSwitchService;

    @Autowired
    private ISwitchInfoService switchInfoService;

    @Autowired
    private IBaseDeviceService baseDeviceService;

    @Autowired
    private IBaseInfoService baseInfoService;

    @Autowired
    private IUserInfoService userInfoService;

    /**
     * 进入铁路段道岔信息列表
     * @return
     */
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public String list(){
        return "roadSwitch/list";
    }

    /**
     * 获取铁路段道岔信息数据
     * @param query
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getList",method = RequestMethod.POST)
    public RoadSwitchQuery getList(RoadSwitchQuery query) {
        try {
            query = roadSwitchService.query(query);
            query.setCode(EnumReturnResult.RETURN_200.getCode());
        } catch (Exception e) {
            log.error("获取铁路段道岔信息列表数据异常", e);
            query.setCode(EnumReturnResult.RETURN_404.getCode());
            query.setMsg("获取铁路段道岔信息数据异常");
        }
        return query;
    }

    /**
     * 进入新增页面
     * @return
     */
    @RequestMapping(value = "/add",method = RequestMethod.GET)
    public String preAdd(){
        return "roadSwitch/add";
    }

    /**
     * 新增铁路段道岔信息
     * @param roadSwitch
     * @param result
     * @return
     */
    @ResponseBody
    @OperationLog(billType ="8",actionType ="0" )
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public BaseResponse add(@Validated RoadSwitch roadSwitch, BindingResult result) {
        BaseResponse response = new BaseResponse();
        try {
            if(result.hasErrors()){
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg("RoadSwitch-add参数有误");
                log.info("RoadSwitch-add参数有误："+result.getAllErrors().toString());
                return response;
            }
            roadSwitchService.add(roadSwitch);
            //选中的道岔均修改状态为正常使用中
            String[] switchCodes = roadSwitch.getSwitchCodeList().split(",");
            List<String> switchCodeList = new ArrayList<>();
            for(String switchCode: switchCodes){
                switchCodeList.add(switchCode);
            }
            SwitchInfo switchInfo = new SwitchInfo();
            switchInfo.setRunType(EnumRunType.USED.getCode());
            switchInfo.setSwitchCodeList(switchCodeList);
            switchInfoService.editRunType(switchInfo);
            response.setCode(EnumReturnResult.RETURN_200.getCode());
            response.setMsg("新增成功");
        } catch (Exception e) {
            log.error("新增道岔信息异常",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("新增失败");
        }
        return response;
    }

    /**
     * 进入修改界面
     * @param id
     * @return
     */
    @RequestMapping(value = "/edit",method = RequestMethod.GET)
    public ModelAndView preEdit(Long id){
        ModelAndView mav = new ModelAndView();
        try{
            RoadSwitch roadSwitch = roadSwitchService.get(id);
            mav.addObject("roadSwitch",roadSwitch);
            mav.setViewName("roadSwitch/edit");
        }catch (Exception e){
            log.error("获取铁路段道岔信息详情失败",e);
            mav.addObject(SystemConstant.ERROR_KEY,"系统异常");
            mav.setViewName("roadSwitch/list");
        }
        return mav;
    }

    /**
     * 修改铁路段道岔信息
     * @param roadSwitch
     * @param result
     * @return
     */
    @ResponseBody
    @OperationLog(billType ="8",actionType ="1" )
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public BaseResponse edit(@Validated RoadSwitch roadSwitch, BindingResult result) {
        BaseResponse response = new BaseResponse();
        try {
            if(result.hasErrors()){
                response.setCode(EnumReturnResult.RETURN_404.getCode());
                response.setMsg("RoadSwitch-edit参数有误");
                log.info("RoadSwitch-edit参数有误："+result.getAllErrors().toString());
                return response;
            }
            //将之前的道岔均修改为未使用
            String[] switchCodesTemp = roadSwitchService.get(roadSwitch.getId()).getSwitchCodeList().split(",");
            List<String> switchCodeListTemp = new ArrayList<>();
            for(String switchCode: switchCodesTemp){
                switchCodeListTemp.add(switchCode);
            }
            SwitchInfo switchInfoTemp = new SwitchInfo();
            switchInfoTemp.setRunType(EnumRunType.UNUSED.getCode());
            switchInfoTemp.setSwitchCodeList(switchCodeListTemp);
            switchInfoService.editRunType(switchInfoTemp);
            //选中的道岔均修改状态为正常使用中
            String[] switchCodes = roadSwitch.getSwitchCodeList().split(",");
            List<String> switchCodeList = new ArrayList<>();
            for(String switchCode: switchCodes){
                switchCodeList.add(switchCode);
            }
            SwitchInfo switchInfo = new SwitchInfo();
            switchInfo.setRunType(EnumRunType.USED.getCode());
            switchInfo.setSwitchCodeList(switchCodeList);
            switchInfoService.editRunType(switchInfo);
            roadSwitchService.edit(roadSwitch);
            response.setCode(EnumReturnResult.RETURN_200.getCode());
            response.setMsg("修改成功");
        } catch (Exception e) {
            log.error("修改铁路段道岔信息异常",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("修改失败");
        }
        return response;
    }

    /**
     * 删除铁路段道岔信息
     * @param id
     * @return
     */
    @ResponseBody
    @OperationLog(billType ="8",actionType ="2" )
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public BaseResponse delete(Long id) {
        BaseResponse response = new BaseResponse();
        try {
            RoadSwitch roadSwitch = roadSwitchService.get(id);
            roadSwitchService.delete(id);
            String[] switchCodesTemp =roadSwitch.getSwitchCodeList().split(",");
            List<String> switchCodeListTemp = new ArrayList<>();
            for(String switchCode: switchCodesTemp){
                switchCodeListTemp.add(switchCode);
            }
            SwitchInfo switchInfoTemp = new SwitchInfo();
            switchInfoTemp.setRunType(EnumRunType.UNUSED.getCode());
            switchInfoTemp.setSwitchCodeList(switchCodeListTemp);
            switchInfoService.editRunType(switchInfoTemp);
            response.setCode(EnumReturnResult.RETURN_200.getCode());
            response.setMsg("删除道岔信息成功");
        } catch (Exception e) {
            log.error("删除道岔信息异常",e);
            response.setCode(EnumReturnResult.RETURN_404.getCode());
            response.setMsg("删除道岔信息失败");
        }
        return response;
    }

    /**
     * 导出用户列表
     * @param response
     * @param query
     * @throws IOException
     */
    @RequestMapping(value = "/exports")
    public void exports(HttpServletResponse response, RoadSwitchQuery query) throws IOException {
        ExcelWriter writer = null;
        OutputStream outputStream = response.getOutputStream();
        try {
            //添加响应头信息
            String fileName = URLEncoder.encode("铁路段道岔信息列表" + DateUtil.DateToString(new Date(), EnumDateStyle.YYYYMMDDHHMMSS), "UTF-8");
            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
            response.setContentType("application/msexcel;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            //实例化 ExcelWriter
            writer = new ExcelWriter(outputStream, ExcelTypeEnum.XLS, true);
            //实例化表单
            Sheet sheet = new Sheet(1, 2, RoadSwitchPojo.class);
            sheet.setSheetName("铁路段道岔信息");
            //获取数据
            List<RoadSwitch> authorityRoles = roadSwitchService.getList(query);
            //输出
            writer.write(authorityRoles, sheet);
            writer.finish();
            outputStream.flush();
        }catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.getOutputStream().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 导入铁路段道岔数据
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/import")
    public FileUploadResponse singleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request)throws Exception{
        FileUploadResponse response = new FileUploadResponse();
        try{
            InputStream inputStream = file.getInputStream();
            ExcelListener listener = new ExcelListener();
            //传入参数
            ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener);
            //读取信息
            excelReader.read(new Sheet(1, 2, RoadSwitchPojo.class));
            List<Object> objList = listener.getDatas();
            for (Object obj : objList){
                RoadSwitchPojo roadSwitchPojo = (RoadSwitchPojo)obj;
                RoadSwitch roadSwitch = new RoadSwitch();
                //判断铁路段道岔编号是否存在
                RoadSwitchQuery roadSwitchQuery = new RoadSwitchQuery();
                roadSwitchQuery.setRoadSwitchCode(roadSwitchPojo.getRoadSwitchCode());
                if(StringUtil.isNotEmpty(roadSwitchService.getList(roadSwitchQuery))){
                    response.setCode(FileConstant.FILE_UPLOAD_ERROR);
                    response.setMsg("铁路段道岔信息中铁路段道岔编号"+roadSwitchPojo.getRoadSwitchCode()+"已存在");
                    return response;
                }
                //判断铁路段道岔型号是否存在
                BaseDeviceQuery baseDeviceQuery = new BaseDeviceQuery();
                baseDeviceQuery.setDeviceModel(roadSwitchPojo.getRoadSwitchModel());
                baseDeviceQuery.setDeviceType(EnumDeviceType.DEVICE_RAILWAY_SWITCH.getCode());
                if(StringUtil.isEmpty(baseDeviceService.getList(baseDeviceQuery))){
                    response.setCode(FileConstant.FILE_UPLOAD_ERROR);
                    response.setMsg("铁路段道岔信息中铁路段道岔型号"+roadSwitchPojo.getRoadSwitchModel()+"不存在");
                    return response;
                }
                //判断局编号是否存在
                BaseInfoQuery baseInfoQuery = new BaseInfoQuery();
                baseInfoQuery.setInfoCode(roadSwitchPojo.getBureauCode());
                baseInfoQuery.setInfoType(EnumInfoType.INFO_BUREAU.getCode());
                if(StringUtil.isEmpty(baseInfoService.getList(baseInfoQuery))){
                    response.setCode(FileConstant.FILE_UPLOAD_ERROR);
                    response.setMsg("铁路段道岔信息中局编号"+roadSwitchPojo.getBureauCode()+"不存在");
                    return response;
                }
                //判断线编号是否存在
                baseInfoQuery.setInfoCode(roadSwitchPojo.getLineCode());
                baseInfoQuery.setInfoType(EnumInfoType.INFO_LINE.getCode());
                if(StringUtil.isEmpty(baseInfoService.getList(baseInfoQuery))){
                    response.setCode(FileConstant.FILE_UPLOAD_ERROR);
                    response.setMsg("铁路段道岔信息中线编号"+roadSwitchPojo.getLineCode()+"不存在");
                    return response;
                }
                //判断车站编号是否存在
                baseInfoQuery.setInfoCode(roadSwitchPojo.getStationCode());
                baseInfoQuery.setInfoType(EnumInfoType.INFO_STATION.getCode());
                if(StringUtil.isEmpty(baseInfoService.getList(baseInfoQuery))){
                    response.setCode(FileConstant.FILE_UPLOAD_ERROR);
                    response.setMsg("铁路段道岔信息中车站编号"+roadSwitchPojo.getStationCode()+"不存在");
                    return response;
                }
                //判断道岔编号是否存在并未使用
                String[] switchCodes = roadSwitchPojo.getSwitchCodeList().split(",");
                for(String str : switchCodes){
                    SwitchInfoQuery switchInfoQuery = new SwitchInfoQuery();
                    switchInfoQuery.setSwitchCode(str);
                    switchInfoQuery.setRunType(EnumRunType.UNUSED.getCode());
                    if(StringUtil.isEmpty(switchInfoService.getList(switchInfoQuery))){
                        response.setCode(FileConstant.FILE_UPLOAD_ERROR);
                        response.setMsg("铁路段道岔信息中道岔编号"+str+"不存在或已被使用");
                        return response;
                    }
                }
                //判断监管员账号是否存在
                UserInfoQuery userInfoQuery = new UserInfoQuery();
                userInfoQuery.setUserAccount(roadSwitchPojo.getSupervisorAccount());
                if(StringUtil.isEmpty(userInfoService.getList(userInfoQuery))){
                    response.setCode(FileConstant.FILE_UPLOAD_ERROR);
                    response.setMsg("铁路段道岔信息中监管员账号"+roadSwitchPojo.getSupervisorAccount()+"不存在");
                    return response;
                }
                //判断维修员账号是否存在
                userInfoQuery.setUserAccount(roadSwitchPojo.getRepairmanAccount());
                if(StringUtil.isEmpty(userInfoService.getList(userInfoQuery))){
                    response.setCode(FileConstant.FILE_UPLOAD_ERROR);
                    response.setMsg("铁路段道岔信息中维修员账号"+roadSwitchPojo.getRepairmanAccount()+"不存在");
                    return response;
                }
                List<String> switchCodeList = new ArrayList<>();
                for(String str : switchCodes){
                    switchCodeList.add(str);
                }
                SwitchInfo switchInfo = new SwitchInfo();
                switchInfo.setRunType(EnumRunType.USED.getCode());
                switchInfo.setSwitchCodeList(switchCodeList);
                switchInfoService.editRunType(switchInfo);
                roadSwitch.setRoadSwitchCode(roadSwitchPojo.getRoadSwitchCode());
                roadSwitch.setRoadSwitchModel(roadSwitchPojo.getRoadSwitchModel());
                roadSwitch.setBureauCode(roadSwitchPojo.getBureauCode());
                roadSwitch.setLineCode(roadSwitchPojo.getLineCode());
                roadSwitch.setStationCode(roadSwitchPojo.getStationCode());
                roadSwitch.setSwitchCodeList(roadSwitchPojo.getSwitchCodeList());
                roadSwitch.setSupervisorAccount(roadSwitchPojo.getSupervisorAccount());
                roadSwitch.setRepairmanAccount(roadSwitchPojo.getRepairmanAccount());
                roadSwitch.setRemark(roadSwitchPojo.getRemark());
                roadSwitchService.add(roadSwitch);
            }
            response.setCode(FileConstant.FILE_UPLOAD_SUCCESS);
            response.setMsg("导入铁路段道岔数据成功");
        }catch (Exception e){
            log.info("导入铁路段道岔数据{}失败",file.getOriginalFilename());
            log.error("导入铁路段道岔数据失败：",e);
            response.setCode(FileConstant.FILE_UPLOAD_ERROR);
            response.setMsg("导入铁路段道岔数据异常");
        }
        return response;
    }
}
